# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Utilities for Managing Temporary Directories and Files

Use this module when a temporary directory and/or temporary files
are needed.

"""


import tempfile
import os
import random
import shutil
import sys

from gvn import platform

def RecursiveRmdir(directory):
  if not os.path.isdir(directory):
    return True

  platform.rmtree(directory)
  return not os.path.isdir(directory)

_TMPDIR = None

def _CleanUp(dir=_TMPDIR):
  if dir is None:
    return True

  if not RecursiveRmdir(dir):
    return False

  return True

def _Setup():
  global _TMPDIR

  if _TMPDIR is not None:
    return True

  _TMPDIR = tempfile.mkdtemp()
  if not _TMPDIR or not os.path.isdir(_TMPDIR):
    _TMPDIR = None
    print >>sys.stderr, "Failed to create temporary directory."
    return False

  return True


def TmpDir():
  """Get the absolute path of the random temporary directory
  currently in use.  The temporary diretory is created if
  it doesn't exist.
  """
  _Setup()
  return _TMPDIR

def SetTmpDir(dir):
  """Set the global temporary directory currently in use.  The
  directory will be created if it does not already exist.
  """
  global _TMPDIR

  _TMPDIR = dir
  if not os.path.isdir(dir):
    os.mkdir(dir)

def RandomTmpSubdir():
  """Get the absolute path of a random temporary subdirectory
  under the main temporary directory currently in use.  The
  temporary subdiretory is created if it doesn't exist.
  """
  _Setup()
  return tempfile.mkdtemp(dir=_TMPDIR)

def TmpSubdir(subdirname):
  """Get the absolute path of a specified temporary subdirectory
  under the main temporary directory currently in use.  The
  temporary subdiretory is created if it doesn't exist.
  """
  _Setup()
  tmp_dir = os.path.join(_TMPDIR, subdirname)
  if not os.path.exists(tmp_dir):
    os.mkdir(tmp_dir)
  return tmp_dir
